package day21;

import java.util.Arrays;
import java.util.Scanner;

public class Homework1 {
    static int nums[]={1,2,3,4,5};
    static Scanner sc=new Scanner(System.in);

    public void traverse(){
        System.out.print("请输入要查看元素的下标（1~5）:");
        int num= sc.nextInt();
        if (num>=1&&num<=5){
            System.out.println("该元素为:"+nums[num-1]);
        }else {
            try{
                throw new ArrayIndexOutOfBoundsException("数组越界异常!");
            } catch (ArrayIndexOutOfBoundsException e) {
                e.printStackTrace();
            }
        }
    }
    public void update(){
        System.out.print("请输入要修改元素的下标（1~5）：");
        int num= sc.nextInt();
        System.out.print("请输入要修改的内容：");
        int n=sc.nextInt();
        if (nums!=null){
            nums[num-1]=n;
            System.out.println("修改成功！");
        }else {
            try{
                throw new NullPointerException("空指针异常！");
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }
    }

    public void delete(){
         System.out.print("请输入要删除的元素:");
         int num=sc.nextInt();
         int j=nums.length;
         boolean b=false;
         for (int i=0;i<nums.length;i++){
             if (nums[i]==num){
                 b=true;
                 j--;
             }
         }

        if (!b) {
            try {
                throw new IllegalArgumentException("该元素不存在!");
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }else {
            int nums2[]=new int[j];
            int k=0;
            for (int i=0;i<nums.length;i++) {
                if (nums[i]!=num) {
                    nums2[k++] = nums[i];
                }
            }
            System.out.println("元素"+num+"删除成功！");
            System.out.println("删除后的数组为："+Arrays.toString(nums2));

        }

    }
    public static void main(String[] args) {
        Homework1 h1=new Homework1();
        while (true){
            System.out.println("*************");
            System.out.println("1.查找元素");
            System.out.println("2.修改元素");
            System.out.println("3.删除元素");
            System.out.println("4.退出");
            System.out.println("*************");
            System.out.print("请输入编号：");
            int s= sc.nextInt();
            switch (s){
                case 1:h1.traverse();break;
                case 2:h1.update();break;
                case 3:h1.delete();break;
                case 4:return;
                default:break;
            }
        }
    }
}
